package com.sh.personnel.security.config.handler;

import com.sh.personnel.security.exception.CaptchaValidateException;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败返回的信息
 * @author 林思浩
 * @date 2020/01/05 17:40
 */
@Component
public class MyAuthFailureHandler extends MyCustomHandler implements AuthenticationFailureHandler {

    private Object code = HttpServletResponse.SC_UNAUTHORIZED; // 401
    private String message;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if(e instanceof CaptchaValidateException) { //验证码验证异常捕获
            code = 704; //验证码异常码
            message =  e.getMessage();
        }else {
            message = "登录失败，请联系管理员！";
        }
        this.responseJson(code, message, response);
    }

}
